package com.jakewharton.rxbinding4.component;

import static com.jakewharton.rxbinding4.internal.Preconditions.checkMainThread;

import com.jakewharton.rxbinding4.internal.Notification;

import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.openharmony.MainThreadDisposable;
import ohos.agp.components.Component;

final class ComponentBoundObservable extends Observable<Object> {
    private final boolean callOnBound;
    private final Component view;

    ComponentBoundObservable(Component view, boolean callOnBound) {
        this.view = view;
        this.callOnBound = callOnBound;
    }

    @Override
    protected void subscribeActual(final Observer<? super Object> observer) {
        if (!checkMainThread(observer)) {
            return;
        }
        Listener listener = new Listener(view, callOnBound, observer);
        observer.onSubscribe(listener);

        view.setBindStateChangedListener(listener);
    }

    static final class Listener extends MainThreadDisposable implements Component.BindStateChangedListener {
        private final Component view;
        private final boolean callOnBound;
        private final Observer<? super Object> observer;

        Listener(Component view, boolean callOnBound, Observer<? super Object> observer) {
            this.view = view;
            this.callOnBound = callOnBound;
            this.observer = observer;
        }

        @Override
        protected void onDispose() {
            view.removeBindStateChangedListener(this);
        }

        @Override
        public void onComponentBoundToWindow(Component component) {
            if (callOnBound && !isDisposed()) {
                observer.onNext(Notification.INSTANCE);
            }
        }

        @Override
        public void onComponentUnboundFromWindow(Component component) {
            if (!callOnBound && !isDisposed()) {
                observer.onNext(Notification.INSTANCE);
            }
        }
    }
}
